<template>
  <div class="dashboard-page">
    <div class="page-header">
      <h1 class="page-title">시스템 개요</h1>
      <p class="page-subtitle">한국 금융 시스템 관리자 센터</p>
    </div>

    <!-- 통계 카드 -->
    <div class="stats-grid">
      <div class="stat-card pending">
        <div class="stat-icon">
          <el-icon size="24"><Clock /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ statsData.pendingDeposits + statsData.pendingWithdraws }}</div>
          <div class="stat-label">처리 대기 신청</div>
        </div>
      </div>

      <div class="stat-card deposits">
        <div class="stat-icon">
          <el-icon size="24"><Top /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ statsData.todayDeposits }}</div>
          <div class="stat-label">금일 충전 건수</div>
        </div>
      </div>

      <div class="stat-card withdraws">
        <div class="stat-icon">
          <el-icon size="24"><Bottom /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ statsData.todayWithdraws }}</div>
          <div class="stat-label">금일 출금 건수</div>
        </div>
      </div>

      <div class="stat-card amount">
        <div class="stat-icon">
          <el-icon size="24"><Money /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ formatAmount(statsData.todayAmount) }}</div>
          <div class="stat-label">금일 거래 금액</div>
        </div>
      </div>
    </div>

    <!-- 빠른 작업 -->
    <div class="quick-actions">
      <h2 class="section-title">빠른 작업</h2>
      <div class="actions-grid">
        <el-card class="action-card" @click="goToDeposits">
          <div class="action-content">
            <el-icon size="32" class="action-icon deposit-icon"><Top /></el-icon>
            <h3>충전 관리</h3>
            <p>사용자 충전 신청 검토</p>
            <el-badge :value="statsData.pendingDeposits" class="action-badge" v-if="statsData.pendingDeposits > 0" />
          </div>
        </el-card>

        <el-card class="action-card" @click="goToWithdraws">
          <div class="action-content">
            <el-icon size="32" class="action-icon withdraw-icon"><Bottom /></el-icon>
            <h3>출금 관리</h3>
            <p>사용자 출금 신청 검토</p>
            <el-badge :value="statsData.pendingWithdraws" class="action-badge" v-if="statsData.pendingWithdraws > 0" />
          </div>
        </el-card>

        <el-card class="action-card" @click="goToUsers">
          <div class="action-content">
            <el-icon size="32" class="action-icon user-icon"><User /></el-icon>
            <h3>사용자 관리</h3>
            <p>사용자 정보 보기</p>
          </div>
        </el-card>

        <el-card class="action-card" @click="goToSettings">
          <div class="action-content">
            <el-icon size="32" class="action-icon settings-icon"><Setting /></el-icon>
            <h3>시스템 설정</h3>
            <p>시스템 설정 관리</p>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 최근 활동 -->
    <div class="recent-activities">
      <h2 class="section-title">최근 활동</h2>
      <el-card>
        <el-table :data="recentActivities" style="width: 100%" v-loading="isLoadingActivities">
          <el-table-column prop="type" label="유형" width="100">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)">{{ getTypeText(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="사용자" width="120" />
          <el-table-column prop="amount" label="금액" width="120">
            <template #default="{ row }">
              {{ formatAmount(row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="상태" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="시간" />
          <el-table-column label="작업" width="120">
            <template #default="{ row }">
              <el-button
                size="small"
                @click="viewDetail(row)"
                v-if="row.status === 'PENDING'"
              >
                처리
              </el-button>
              <span v-else class="text-gray-400">처리 완료</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Clock, Top, Bottom, Money, User, Setting } from '@element-plus/icons-vue'
import { api, type ApiResponse } from '@/utils/request'

type ActivityType = 'DEPOSIT' | 'WITHDRAW'
type ActivityStatus = 'PENDING' | 'CONFIRMED' | 'FAILED' | 'CANCELLED' | string

interface OverviewStatsData {
  pendingCount: number
  stats: {
    confirmed: {
      count: number
      amount: number
    }
  }
}

interface TransactionRecord {
  id: number | string
  user: {
    name: string
  }
  amount: number | string
  status: ActivityStatus
  createdAt: string
}

interface TransactionListData {
  records: TransactionRecord[]
}

interface ActivityItem {
  id: string
  type: ActivityType
  userName: string
  amount: number
  status: ActivityStatus
  createdAt: string
  originalData: TransactionRecord
}

interface StatsData {
  pendingDeposits: number
  pendingWithdraws: number
  todayDeposits: number
  todayWithdraws: number
  todayAmount: number
}

const router = useRouter()

const statsData = ref<StatsData>({
  pendingDeposits: 0,
  pendingWithdraws: 0,
  todayDeposits: 0,
  todayWithdraws: 0,
  todayAmount: 0
})

const recentActivities = ref<ActivityItem[]>([])
const isLoadingActivities = ref(false)

// 금액 포맷
const formatAmount = (amount: number): string => {
  return amount.toLocaleString('ko-KR') + ' ₩'
}

// 유형 태그 타입 반환
const getTypeTagType = (type: ActivityType) => {
  return type === 'DEPOSIT' ? 'success' : 'warning'
}

// 유형 텍스트 반환
const getTypeText = (type: ActivityType) => {
  return type === 'DEPOSIT' ? '충전' : '출금'
}

// 상태 태그 타입 반환
const getStatusTagType = (status: ActivityStatus) => {
  switch (status) {
    case 'PENDING': return 'warning'
    case 'CONFIRMED': return 'success'
    case 'FAILED': return 'danger'
    default: return 'info'
  }
}

// 상태 텍스트 반환
const getStatusText = (status: ActivityStatus) => {
  switch (status) {
    case 'PENDING': return '대기'
    case 'CONFIRMED': return '승인 완료'
    case 'FAILED': return '거절'
    case 'CANCELLED': return '취소'
    default: return '알 수 없음'
  }
}

// 통계 데이터 로드
const loadStats = async (): Promise<void> => {
  try {
    const [depositStats, withdrawStats] = await Promise.all([
      api.get<ApiResponse<OverviewStatsData>>('/api/admin/deposit/stats/overview'),
      api.get<ApiResponse<OverviewStatsData>>('/api/admin/withdraw/stats/overview')
    ])

    if (depositStats.success && withdrawStats.success) {
      statsData.value = {
        pendingDeposits: depositStats.data.pendingCount,
        pendingWithdraws: withdrawStats.data.pendingCount,
        todayDeposits: depositStats.data.stats.confirmed.count,
        todayWithdraws: withdrawStats.data.stats.confirmed.count,
        todayAmount: depositStats.data.stats.confirmed.amount + withdrawStats.data.stats.confirmed.amount
      }
    }
  } catch (error) {
    console.error('통계 데이터 로드 실패:', error)
  }
}

// 최근 활동 로드
const loadRecentActivities = async (): Promise<void> => {
  try {
    isLoadingActivities.value = true

    const [deposits, withdraws] = await Promise.all([
      api.get<ApiResponse<TransactionListData>>('/api/admin/deposit/list?limit=5'),
      api.get<ApiResponse<TransactionListData>>('/api/admin/withdraw/list?limit=5')
    ])

    const activities: ActivityItem[] = []

    if (deposits.success) {
      activities.push(
        ...deposits.data.records.map((item): ActivityItem => ({
          id: `deposit_${item.id}`,
          type: 'DEPOSIT',
          userName: item.user.name,
          amount: Number(item.amount),
          status: item.status,
          createdAt: new Date(item.createdAt).toLocaleString('ko-KR'),
          originalData: item
        }))
      )
    }

    if (withdraws.success) {
      activities.push(
        ...withdraws.data.records.map((item): ActivityItem => ({
          id: `withdraw_${item.id}`,
          type: 'WITHDRAW',
          userName: item.user.name,
          amount: Number(item.amount),
          status: item.status,
          createdAt: new Date(item.createdAt).toLocaleString('ko-KR'),
          originalData: item
        }))
      )
    }

    // 시간순 정렬
    activities.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
    recentActivities.value = activities.slice(0, 10)

  } catch (error) {
    console.error('최근 활동 로드 실패:', error)
  } finally {
    isLoadingActivities.value = false
  }
}

// 빠른 작업 내비게이션
const goToDeposits = () => {
  router.push('/deposit-management')
}

const goToWithdraws = () => {
  router.push('/withdraw-management')
}

const goToUsers = () => {
  ElMessage.info('사용자 관리 기능은 준비 중입니다.')
}

const goToSettings = () => {
  ElMessage.info('시스템 설정 기능은 준비 중입니다.')
}

// 상세 보기
const viewDetail = (row: any) => {
  if (row.type === 'DEPOSIT') {
    router.push('/deposit-management')
  } else {
    router.push('/withdraw-management')
  }
}

onMounted(() => {
  loadStats()
  loadRecentActivities()
})
</script>

<style scoped lang="scss">
.dashboard-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 32px;

  .page-title {
    font-size: 32px;
    font-weight: 700;
    color: #1a202c;
    margin: 0 0 8px 0;
  }

  .page-subtitle {
    font-size: 16px;
    color: #64748b;
    margin: 0;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  border: 1px solid #e2e8f0;
  transition: transform 0.2s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  }

  .stat-icon {
    width: 56px;
    height: 56px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
  }

  .stat-content {
    flex: 1;

    .stat-value {
      font-size: 28px;
      font-weight: 700;
      color: #1a202c;
      line-height: 1;
      margin-bottom: 4px;
    }

    .stat-label {
      font-size: 14px;
      color: #64748b;
    }
  }

  &.pending .stat-icon {
    background: #fef3c7;
    color: #d97706;
  }

  &.deposits .stat-icon {
    background: #dcfce7;
    color: #16a34a;
  }

  &.withdraws .stat-icon {
    background: #fce7f3;
    color: #e11d48;
  }

  &.amount .stat-icon {
    background: #dbeafe;
    color: #2563eb;
  }
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
  margin: 0 0 16px 0;
}

.quick-actions {
  margin-bottom: 40px;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
}

.action-card {
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  position: relative;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
  }

  .action-content {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;

    .action-icon {
      padding: 12px;
      border-radius: 12px;
      background: #f5f7ff;

      &.deposit-icon {
        color: #16a34a;
        background: rgba(22, 163, 74, 0.1);
      }

      &.withdraw-icon {
        color: #e11d48;
        background: rgba(225, 29, 72, 0.1);
      }

      &.user-icon {
        color: #2563eb;
        background: rgba(37, 99, 235, 0.1);
      }

      &.settings-icon {
        color: #7c3aed;
        background: rgba(124, 58, 237, 0.1);
      }
    }

    h3 {
      font-size: 18px;
      font-weight: 600;
      color: #1f2937;
      margin: 0;
    }

    p {
      font-size: 14px;
      color: #6b7280;
      margin: 0;
    }
  }

  .action-badge {
    position: absolute;
    top: 16px;
    right: 16px;
  }
}

.recent-activities {
  margin-top: 40px;
}

:deep(.el-table) {
  font-size: 13px;
}
</style>
